package org.bot.socket.auth;

import com.alibaba.fastjson.JSONObject;
import org.bot.socket.config.SocketConfig;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.UUID;

@Component
public class CertificateManage {

    private static final String path = System.getProperty("user.dir") + "/config/cer/bot-client-certificate.cer";
    private static final String keyPath = System.getProperty("user.dir") + "/config/cer/bot-client.key";
    private static final Scanner scanner = new Scanner(System.in);

    public static SocketConfig readCertificate() {
        final File file = new File(keyPath);
        String authCode;
        if (!file.exists()) {
            System.out.println("客户端暂未激活，需要输入授权码激活使用.");
            System.out.print("授权码:");
            authCode = scanner.nextLine();
        } else {
            try {
                authCode = new String(Files.readAllBytes(Paths.get(keyPath)), StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new RuntimeException("客户端认证失败");
            }
        }

        File cer = new File(path);
        if (!cer.exists()) {
            throw new RuntimeException("未找到客户端证书");
        }
        try {
            final byte[] bytes = Files.readAllBytes(Paths.get(path));
            try {
                final String decrypt = AESUtils.decrypt(bytes, authCode);
                final JSONObject cerJson = JSONObject.parseObject(decrypt);
                SocketConfig config = new SocketConfig();
                config.setUrl(cerJson.getString("url"));
                config.setClientId(cerJson.getString("clientId"));
                config.setSecretKey(cerJson.getString("secret"));
                config.setMac(cerJson.getString("deviceId"));
                config.setStatus(cerJson.getBooleanValue("status"));
                return config;
            } catch (Exception e) {
                throw new RuntimeException("加载证书错误");
            }
        } catch (IOException e) {
            throw new RuntimeException("客户端证书错误");
        }
    }

    public static void writeCertificate(SocketConfig config) throws Exception {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(keyPath))) {
            writer.write(uuid);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        JSONObject tmp = new JSONObject();
        tmp.fluentPut("url", config.getUrl())
                .fluentPut("clientId", config.getClientId())
                .fluentPut("secret", config.getSecretKey())
                .fluentPut("deviceId", config.getMac())
                .fluentPut("status", true);

        byte[] encrypt = AESUtils.encrypt(tmp.toString(), uuid);
        try (FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(encrypt);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
